import { defineStore } from 'pinia'

const useAuthStore = defineStore('auth', {
    state: () => ({
        auth: loadData()
    }),
    actions: {
        setMerchant(data: any) {
            if (this.auth.merchant === undefined) {
                this.auth.merchant = {}
            }
            this.auth.merchant = Object.assign(this.auth.merchant, data)
            saveData(this.auth)
        },
        setBank(data: any) {
            if (this.auth.bank === undefined) {
                this.auth.bank = {}
            }
            this.auth.bank = Object.assign(this.auth.bank, data)
            saveData(this.auth)
        },
        setAuth(data: any){
            if (this.auth.authentication === undefined) {
                this.auth.authentication = {}
            }
            this.auth.authentication = Object.assign(this.auth.authentication, data)
            saveData(this.auth)
        },
        clearData(){
            this.auth = {}
            uni.removeStorageSync('auth_data')
        },
        resetParamByName(name: string){
            outer:
            for (let key in this.auth) {
                if (typeof this.auth[key] == 'object') {
                    for (let target in this.auth[key]) {
                        if (target == name) {
                            this.auth[key][name] = undefined
                            saveData(this.auth)
                            break outer
                        }
                    }
                }
            }
        }
    }
})

function loadData() {
    return uni.getStorageSync('auth_data')
}

function saveData(data: any) {
    uni.setStorageSync('auth_data', data)
}

export default useAuthStore
